package com.hwhhhh.graduationproject.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;

/**
 * @Description detail
 * Created by Hwhhhh on 2021/3/4 15:57
 */
public class ImageUtils {
    public static final String USER = "//users//";
    private static final String ROOT_URL="http://localhost:8081//api//images", ROOT_PATH = "E://Intellij IDEA//image-storage";

    /**
     * 上传一组图片
     * @param files 一组图片
     * @param path 图片保存路径，即 HOUSE or USER
     * @return
     * @throws IOException
     */
    public static String[] uploadImages(MultipartFile[] files, String path) throws IOException {
        String[] urls = new String[files.length];

        for (int i = 0; i <files.length; i ++) {
            //用时间戳设置新的文件名
            Date date = new Date();
            String filename = Long.toString(date.getTime());
            String originalFilename = files[i].getOriginalFilename();
            String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //创建文件
            File newFile = new File(ROOT_PATH + path);
            if (!newFile.exists()) {
                newFile.mkdirs();
            }
            //打开输入输出准备保存文件
            FileInputStream inputStream = (FileInputStream) files[i].getInputStream();
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(ROOT_PATH + path + filename + prefix));
            byte[] bs = new byte[1024];
            int len;
            while ((len = inputStream.read(bs)) != -1) {
                bos.write(bs, 0, len);
            }
            bos.flush();
            bos.close();
            urls[i] = ROOT_URL + path + filename + prefix;
        }
        return urls;
    }

    public static String uploadImage(MultipartFile file, String path) throws IOException{
        MultipartFile[] multipartFiles = new MultipartFile[]{
                file
        };
        return uploadImages(multipartFiles, path)[0];
    }
}
